import os
import subprocess
import threading

def read_stream(stream, callback):
    with stream:
        for line in iter(stream.readline, ""):
            callback(line.strip())

def execute_scripts_in_order(scripts_with_args):
    for index, (script, args) in enumerate(scripts_with_args, start=1):
        if not os.path.isfile(script):
            print(f"Script not found: {script}")
            continue
        
        print(f"执行脚本 {index}/{len(scripts_with_args)}: {os.path.basename(script)}...")

        try:
            command = f"start cmd /C python {script} {' '.join(args)}"

            process = subprocess.Popen(
                command, 
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding="utf-8"
            )

            stdout_thread = threading.Thread(
                target=read_stream,
                args=(process.stdout, lambda x: print(f"Output: {x}", flush=True))
            )
            stderr_thread = threading.Thread(
                target=read_stream,
                args=(process.stderr, lambda x: print(f"Error: {x}", flush=True))
            )

            stdout_thread.start()
            stderr_thread.start()

            stdout_thread.join()
            stderr_thread.join()

            process.wait()

            if process.returncode != 0:
                print(f"Script {script} failed with return code {process.returncode}")

        except Exception as e:
            print(f"Failed to execute {script}: {e}")

if __name__ == "__main__":
    scripts_with_args = [
        (".\\script\\train1.py", []),
        (".\\script\\train2.py", []),
        (".\\script\\train3.py", []),
    ]

    execute_scripts_in_order(scripts_with_args)
